<template>
  <div class="newTeacher">
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/institutions' }">机构列表</el-breadcrumb-item>
      <el-breadcrumb-item :to="{ path: '/institutions/agency' }">列表详情</el-breadcrumb-item>
      <template v-if="this.$route.params.add == 'add'">
        <el-breadcrumb-item>新增教师管理</el-breadcrumb-item>
      </template>
      <template v-else>
        <el-breadcrumb-item>教师管理详情</el-breadcrumb-item>
      </template>
    </el-breadcrumb>

    <div class="aroundOf">新增教师</div>
    <div class="newTeacher_o">
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <el-tab-pane label="单个新增" name="first"></el-tab-pane>
        <el-tab-pane label="批量新增" name="second"></el-tab-pane>
      </el-tabs>

      <div v-if="activeName == 'first'" class="primary">
        <div class="real">
          <!-- <p>真实姓名：</p>
          <el-input placeholder="请输入内容" v-model.lazy.trim="input" clearable style="width: 30%;"></el-input>
          <span>（必填）请输入20个字符以内的用户名</span> -->
          <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm" style="width: 50%;">
            <el-form-item label="真实姓名：" prop="name">
              <div style="display: flex;flex-wrap: wrap;">
                <el-input v-model="ruleForm.name"  style="width: 300px;margin: 0 30px 10px 0;" clearable></el-input>
                <span>(必填)请输入10个字符以内的用户名</span>
              </div>
            </el-form-item>
            <el-form-item>
              <!-- <el-button type="primary" @click="submitForm('ruleForm')">提交</el-button> -->
              <el-button type="primary" @click="addTeacher('ruleForm')" :disabled="isDisabled">添加教师</el-button>
            </el-form-item>
          </el-form>
        </div>
        <!-- <el-button type="primary" @click="addTeacher">添加教师</el-button> -->
      </div>

      <div v-else>
        <div class="container download">
          <div class="row downloadsEa">
            <div class="col col-xxl-6 col-lg-12 col-xl-6">
              <div class="download_l">
                <h1>1.模板下载</h1>
                <p>
                  请先下载模板，并按照模板格式完成数据填写，填写候在右侧完成数据导入
                </p>
                <el-button type="primary" @click="download" class="download_btn" >下载模板</el-button>
                <h1>2.数据导入</h1>
                <p>按页面提示，将数据表格拖入下方，导入数据</p>
                <div class="intoThe">
                  <p>上传文件：</p>
                  <el-upload
                    class="upload-demo"
                      drag
                      ref="upload"
                      :file-list="fileList"
                      :action=" baseURL + '/tearUser/import'"
                      :on-success="onSuccess"
                      multiple
                      :auto-upload="false">
                    <i class="el-icon-upload"></i>
                    <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                  </el-upload>
                </div>
                <el-button type="primary" style="width: 120px;margin: 10px;" @click="submitUpload">导入</el-button>
              </div>
            </div>
            
            <div class="col col-xxl-6 col-lg-12 col-xl-6">
              <div class="download_r">
                <h1>3.数据确认</h1>
                <el-button @click="deletEe" class="deletEe">删除</el-button>
                <el-table v-if="disappear" :data="gridData" style="width: 100%;margin-top: 66px;" max-height="250" :header-cell-style="{ background: '#f2f2f2', color: '#333', fontWeight: 600, }">
                  <el-table-column prop="name" label="用户名" align="center"> </el-table-column>
                  <el-table-column label="机构所属" align="center">
                    <template slot-scope="scope">
                      <span class="scope_span1">• {{ scope.row.iname == '' ? '--' : scope.row.iname }}</span>
                    </template>
                  </el-table-column>
                  <el-table-column fixed="right" label="操作" align="center">
                    <template slot-scope="scope">
                      <el-button @click.native.prevent="deleteRow(scope.$index, gridData)" type="text" size="small" >
                        删除
                      </el-button>
                    </template>
                  </el-table-column>
                </el-table>
                <div class="batchEs">
                  <el-button type="primary" @click="batchAdd" class="batchAdd">批量添加学生</el-button>
                </div>
              </div>
            </div>

          </div>
        </div>
      </div>

    </div>

  </div>
</template>

<script>
import { validateRealName } from '../../utils/check';
import { base } from '../../api/axiosFun';
export default {
  data() {
    return {
      baseURL: '',
      activeName: 'first',
      disappear: true,
      fileList: [],
      // 真实姓名
      ruleForm: { name: '', },
      rules: { name: [{ required: true, trigger: 'blur', validator: validateRealName }], },
      isDisabled: false,
      gridData: [],
    }
  },
  mounted(){
    this.baseURL = base;
    if(this.$route.params.add != 'add') {
      this.ruleForm.name = this.$route.params.zhename;
      this.isDisabled = true;
    }
  },
  methods: {
    // 标签页切换
    handleClick(tab, event) {
      console.log(tab, event);
    },
    // 添加教师
    addTeacher(formName) {  // 在这里需要调用后台接口判断是否已经存在真实姓名
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.$http.institutions.UpdateTeacherTear({zhename: this.ruleForm.name,id: JSON.parse(sessionStorage.getItem('userData')).id}).then( result => {
            this.$message({
              message: '添加成功',
              type: 'warning'
            });
            setTimeout( () => {
              this.$router.push({ path: '/institutions/agency' })
            },2500)
          })
        }else {
          this.$message({
            message: '真实姓名不能为空',
            type: 'warning'
          });
        }
      })
    },
    // 下载模板
    download() {
      this.$http.institutions.UpdateTeacherDaochu().then( result => {
        console.log(result);
        const fileName = '下载的文件';
        // const url = window.URL.createObjectURL(new Blob([res]));
        const link = document.createElement('a');
        link.style.display = 'none';
        if(process.env.NODE_ENV == 'development'){       // 开发环境
          link.href = 'http://192.168.1.146:9001/bzsz/tearUser/Daochu';
        }else if(process.env.NODE_ENV == 'production'){  // 生产环境或者叫做线上的环境
          link.href = 'http://xuexi.bzszxr.com/bzsz/tearUser/Daochu';
        }else {   // 测试环境http://admin-test.bzszxr.com/bzsz
          // link.href = 'http://test.bzszxr.com/bzsz/tearUser/Daochu';
          link.href = 'http://admin-test.bzszxr.com/bzsz/tearUser/Daochu';
        };
        // link.href = 'http://192.168.1.146:9001/bzsz/tearUser/Daochu';
        link.setAttribute('download', fileName + '.xls');
        document.body.appendChild(link);
        link.click();
        // 下载完成移除元素
        document.body.removeChild(link)
        // 释放掉blob对象
        // window.URL.revokeObjectURL(url)UpdateTeacherImport
      })
    },
    
    // 批量新增操作
    //导入按钮
    submitUpload() { this.$refs.upload.submit(); },
    // 上传成功后展示
    onSuccess(response, file, fileList){
      if(response.code == 200 || response.code == 0 || response.code == 201){
        this.$message({
          message: '导入成功',
          type: 'success'
        });
        this.nameDisalong = file.name;
        this.gridData = response.data;
      } else if(response.code == 501) {
        this.fileList = [];
        this.$message({
          message: response.errorMessage,
          type: 'warning'
        });
      }
    },
    // 右侧删除表格
    deletEe() {
      console.log("右侧删除表格");
      this.gridData = [];
    },
    // 表格删除
    deleteRow(index, rows) {
      rows.splice(index, 1);
    },
    // 批量添加学生按钮
    batchAdd(){
      this.$http.institutions.UpdateTeacheImportAdd({userTearImplAdds: this.gridData}).then(result=>{
        console.log(result);
      })
    }
  }
}
</script>

<style scoped>
@import '../../assets/css/institutions/newTeacher.scss';
</style>